package com.knowledgePointsByMyTest.JavaBIO;

import java.io.*;
import java.net.Socket;

/**
 * @author yulongtian
 * @create 2024-11-04 10:48
 */
public class BIOClient {
    public static void main(String[] args) {
        Socket socket = null;
        BufferedReader in = null;
        BufferedWriter out = null;
        try {
            socket = new Socket("127.0.0.1", 8888);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            System.out.println("准备向服务端写数据！");
            //向服务端写数据
            out.write("hello server, i am client ! \n");
            out.flush();
            //接收来自服务端的数据
            String line = in.readLine();
            System.out.println("成功接收来自服务端的数据：" + line);
        } catch (Exception e) {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }
}
